package com.dongqb.exe;

import java.awt.EventQueue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import javax.management.RuntimeErrorException;
import javax.swing.JOptionPane;

import com.dongqb.common.CacheData;
import com.dongqb.common.MyUtil;
import com.dongqb.service.LoadDataService;
import com.dongqb.service.LoadStockOnTime;
import com.dongqb.win.MainWinListener;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.setting.Setting;

public class MainExe {

	public static void main(String[] args) {
		try {
			init();
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
					CacheData.mainWin = new MainWinListener();
					CacheData.mainWin.frame.setVisible(true);
					CacheData.mainWin.initData();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public static void init() throws Exception {
		CacheData.runPatch = MyUtil.getPath();
		File dbFile = new File(CacheData.runPatch + "\\db.db3");
		// 如果目录下没有文件，则复制一个出去
		if (!dbFile.exists()) {
			InputStream in = MainExe.class.getResourceAsStream("/com/dongqb/exe/db.db3");
			IoUtil.copy(in, new FileOutputStream(dbFile));
		}
		// 加载数据库
		CacheData.loadService = new LoadDataService();
		if (!CacheData.loadService.testConnect()) {
			JOptionPane.showMessageDialog(null, "数据连接失败", "严重错误!", JOptionPane.ERROR);
			throw new RuntimeException("数据连接失败");
		}
		// 加载配置文件
		CacheData.setting = new Setting(FileUtil.touch(CacheData.runPatch + "\\config.properties"),
				CharsetUtil.CHARSET_UTF_8, true);
		CacheData.setting.store();
		// 执行刷新功能
		CacheData.onTimeService = new LoadStockOnTime();
		CacheData.onTimeService.start();
	}
}
